package net.confinanz.client.frontend;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.JFrame;
import javax.swing.UIManager;

import net.confinanz.config.ClientConfig;

import jd.crypt.JDCrypt;
import jd.utils.JDHexUtils;


public class Loader {
	
	public static final String KONFIGURATIONSDATEI 		= "config.cfg";
	public static final String TITEL					= "Confinanz Verwaltung";

	public static void main(String[] args) {
		
		try {
			preSetup();
			UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaBlueIceLookAndFeel");
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		
		new Login();
	}
	
	private static void preSetup() {
        try {
            String key = JDCrypt.decrypt(JDHexUtils.getByteArray("4a94286634a203ada63b87c54662227252490d6f10e421b7239c610138c53e4c51fc7c0a2a8a18a0a2c0a40191b1186f"), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 11, 12, 13, 14, 15, 16 });
            if (key != null) {
                String[] li = { "Licensee=AppWork UG", "LicenseRegistrationNumber=289416475", "Product=Synthetica", "LicenseType=Small Business License", "ExpireDate=--.--.----", "MaxVersion=2.999.999" };
                UIManager.put("Synthetica.license.info", li);
                UIManager.put("Synthetica.license.key", key);
            }
        } catch (final Throwable e) {
        	System.out.println("Bitte wenden Sie sich an den Systemadministrator");
        }
    }
	
	public static void centerFrame(JFrame frame) {
		Dimension resolution 		= Toolkit.getDefaultToolkit().getScreenSize();
		frame.setLocation(((int)(resolution.getWidth() - frame.getWidth()) / 2),
				((int)(resolution.getHeight() - frame.getHeight()) / 2));
	}
	
	public static ClientConfig loadConfigFromFile() {
		ObjectInputStream configFile;
		ClientConfig config;
		try {
			configFile = new ObjectInputStream(new FileInputStream(Loader.KONFIGURATIONSDATEI));
			config = (ClientConfig) configFile.readObject();
			configFile.close();
			System.out.println("Konfigurationsdatei erfolgreich gelesen.");
		} catch (Exception ignored) {
			config = new ClientConfig();
			System.out.println("Die Konfigurationsdatei konnte nicht gelesen werden. Standardkonfigurationen wurden geladen.");
		}
		return config;
	}

	public static void saveConfigToFile(ClientConfig config) {
		ObjectOutputStream configDatei;

		File outputFile = new File(Loader.KONFIGURATIONSDATEI);
		try {
			configDatei = new ObjectOutputStream(new FileOutputStream(outputFile));
			configDatei.writeObject(config);
			configDatei.close();
		} catch (Exception e) {
			System.out.println("Fehler beim Schreiben der Konfigurationsdatei.");
		}
	}
}